#include"sock_init.h"
#define IPS "ips="
#define PORT "port="
#define LISTREN "lismax="

struct sock_info
{
    char ips[32];
    short port;
    int lismax;
};

int read_sock_conf(struct sock_info *fp)
{
    if(fp==NULL)
    {
        return -1;
    }

    FILE *fd=fopen("socket_info.conf","r");
    if(fd==NULL)
    {
        printf("open sock_info.conf err\n");
        return -1;
    }
      int index=0;

    while (1)
    {
        char buff[128]={0};
        char *s=fgets(buff,128,fd);
        if(s==NULL)
        {
            break;
        }

        index++;
        if(s[0]=='#'||s[0]=='\n')
        {
            continue;
        }
        s[strlen(s)-1]=0;
        if(strncmp(s,IPS,strlen(IPS))==0)
        {
            strcpy(fp->ips,s+strlen(IPS));
        }
        else if(strncmp(s,PORT,strlen(PORT))==0)
        {
            fp->port=atoi(s+strlen(PORT));
        }
        else if(strncmp(s,LISTREN,strlen(LISTREN))==0)
        {
            fp->lismax=atoi(s+strlen(LISTREN));
        }
        else
        {
            printf("不识别的参数line:%d\n",index);
        }   
        
        

    }
    fclose(fd);
   
    return 0;
    
}

int socket_init()
{
    struct sock_info dt;
    int c=read_sock_conf(&dt);
    if(c==-1)
    {
        return -1;
    }
    printf("ip=%s\n",dt.ips);
    printf("port=%d\n",dt.port);
    printf("lismax=%d\n",dt.lismax);
    int  sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd==-1)
    {
        return -1;
    }

    struct sockaddr_in saddr;
    memset(&saddr,0,sizeof(saddr));
    saddr.sin_family=AF_INET;
    saddr.sin_port=htons(dt.port);
    saddr.sin_addr.s_addr=inet_addr(dt.ips);
    int res=bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
    if(res==-1)
    {
        return -1;
    }
    res=listen(sockfd,dt.lismax);
    if(res==-1)
    {
        return -1;
    }
    return sockfd;
}
